import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';

class ListViewFagPage extends StatefulWidget {
  const ListViewFagPage({Key? key}) : super(key: key);

  @override
  State<ListViewFagPage> createState() => _ListViewFagPageState();
}

class _ListViewFagPageState extends State<ListViewFagPage> {
  // 多订阅流方式来创建
  StreamController<int> _streamController = new StreamController.broadcast();
  // 滑动控制器
  ScrollController _scrollController = new ScrollController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:Text("ListView 获取当前显示的Widget位置")
      ),
      backgroundColor: Color(0xfff2f2f2),
      body: Stack(
        alignment: Alignment.center,
        children: [
          // 第一层的列表
          Positioned.fill(child:  buildListView()),
       
        // 第二层的显示标签
        Positioned(
          child: buildButtonFlag(),
          right: 10,)
        
        ],
      )
    );
    
  }
  buildListView(){
    return ListView.custom(
      // 控制器
      controller: _scrollController,
      // 缓存空间
      cacheExtent: 0.0,
      //自定义代理
      childrenDelegate: 
      CustomScrollDelegate((BuildContext context,int index){
        return Demo14ListItemWidget(index:index);
      },
      // 条目个数
      itemCount:100,
      // 滑动回调
      scrollCallBack:(int firstIndex,int lastIndex){
        print("firstIndex $firstIndex lastIndex $lastIndex");
        _streamController.add(firstIndex);
      }
      )
    );
  }
  
  buildButtonFlag(){
    return Column(
      children: [
        // 椭圆裁剪
        ClipOval(
          child: Container(
            color: Colors.blueGrey,
            child: TextButton(
              onPressed: (){
                print("点击");
                _scrollController.animateTo(0, duration: Duration(microseconds: 400), curve: Curves.ease);
              }, 
              
              child: StreamBuilder<int>(
                // 绑定流控制器
                stream: _streamController.stream,
                // 初始化显示的数据
                initialData: 0,
                builder: (BuildContext context,AsyncSnapshot<dynamic> snapshot){
                  return Text(
                  "${snapshot.data}",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22,
                    fontWeight: FontWeight.w500
                  ),
                  );
                },
              )),
          ),
        )
      ],
      );
  }

  @override
  void dispose() {
    
    _streamController.close();
    super.dispose();
  }
  
}

class Demo14ListItemWidget extends StatefulWidget{
  final int index;
  const Demo14ListItemWidget({ Key ?key,required this.index}):super(key:key);
  @override
  State<StatefulWidget> createState() {
   return _Demo14ListItemWidgetState();
  }
}

class _Demo14ListItemWidgetState extends State<Demo14ListItemWidget>{
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      color:Colors.white,
      padding: EdgeInsets.all(8),
      child: Row(
        children: [
          // 左侧图片
          Image.asset("assets/germany.png",width: 100,),
          SizedBox(width:10),
          // 右侧文字
          Expanded(
            child: Column(
              crossAxisAlignment:CrossAxisAlignment.start,
              children: [
                // 第一行文字
                Text("学习flutter ${widget.index}",
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 16
                  ),
                ),
                SizedBox(height: 10),
                // 第二行文字
                Text("加油啊~~~~",
                  style: TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: 14
                    ),
                )
              ],
            )
            )

        ],
      ),
      );
      
    
  }
}

class CustomScrollDelegate extends SliverChildBuilderDelegate{
  // 定义滑动
  Function(int firstIndex,int lastIndex) scrollCallBack;
  // 构造函数
 CustomScrollDelegate(
   builder,{required int itemCount, required this.scrollCallBack }):super(builder,childCount: itemCount);
   @override
  double? estimateMaxScrollOffset(int firstIndex, int lastIndex, double leadingScrollOffset, double trailingScrollOffset) {
    if(scrollCallBack != null){
      scrollCallBack(firstIndex,lastIndex);
    }


    return super.estimateMaxScrollOffset(firstIndex, lastIndex, leadingScrollOffset, trailingScrollOffset);
  }

}